﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using AAA.Writer.Format;

namespace AAA.Writer
{
    public class TextWriter : AbstractWriter
    {
        public override bool Write(AAA.ResultSet.IResultSet resultSet, object oFormat)
        {
            bool isSuccess = false;
            TextFormat textFormat = (TextFormat)oFormat;
            StreamWriter sw = null;
            string strLine;

            try
            {
                sw = new StreamWriter(textFormat.Filename, textFormat.IsAppend, textFormat.Encoding);

                strLine = "";
                for (int i = 0; i < resultSet.ColumnCount; i++)
                    strLine += textFormat.Delimeter + resultSet.ColumnNames()[i];

                sw.WriteLine(strLine.Substring(textFormat.Delimeter.Length));

                resultSet.Reset();
                while (resultSet.Read())
                {
                    strLine = "";
                    for (int i = 0; i < resultSet.ColumnCount; i++)
                        strLine += textFormat.Delimeter + resultSet.Cells(i).ToString();
                    sw.WriteLine(strLine.Substring(textFormat.Delimeter.Length));
                }
                sw.Flush();

                isSuccess = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message + "," + ex.StackTrace;
            }
            finally
            {
                if (sw != null)
                    sw.Close();
            }
            return isSuccess;
        }

        public override bool Write(Dictionary<string, CellValue> dicValue, object oFormat)
        {
            throw new Exception("The method or operation is not implemented.");
        }
    }
}
